<?php
/**
 * Created by PhpStorm.
 * User: 祈晴宝宝
 * Date: 2018/3/10
 * Time: 15:39
 */
namespace craw;
class CacheHelper
{
    protected $dir = '';
    protected $flag=false;
    protected $mObj;

    public function __construct()
    {
        if (class_exists("Memcache"))
        {
            $this->mObj = new Memcache();
            $this->flag = $this->mObj->connect("127.0.0.1", 11211);
        }


        if (!$this->flag)
        {
            $this->dir = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'cache';
            if (is_dir($this->dir))
            {
                return;
            }
            @mkdir($this->dir);
        }
    }



    public function Set($key, $value, $expire = 360)
    {
        if ($this->flag)
        {
            $this->mObj->set(md5($key), $value, 0, $expire);
        }
        else
        {
            $data = array(
                'time' => time(),
                'expire' => $expire,
                'value' => $value
            );
            @file_put_contents($this->dir . DIRECTORY_SEPARATOR . md5($key) . 'cache', serialize($data));
        }

    }

    public function Get($key)
    {
        if ($this->flag)
        {
            return $this->mObj->get(md5($key));
        }
        else
        {
            $file = $this->dir . DIRECTORY_SEPARATOR . md5($key) . 'cache';
            if (!file_exists($file))
            {
                return false;
            }
            $str = @file_get_contents($file);
            if (empty($str))
            {
                return false;
            }
            $data = @unserialize($str);
            if (!isset($data['time']) || !isset($data['expire']) || !isset($data['value']))
            {
                return false;
            }
            if ($data['time'] + $data['expire'] < time())
            {
                return false;
            }
            return $data['value'];
        }

    }

    public function clean()
    {

        if ($this->flag)
        {
            $this->mObj->flush();
        }else
        {
            if (!empty($this->dir) && is_dir($this->dir))
            {
                @rmdir($this->dir);
            }
            $files = scandir($this->dir);
            foreach ($files as $file)
            {
                @unlink($this->dir . DIRECTORY_SEPARATOR . $file);
            }
        }

    }
}